<?php
namespace app\index\controller;
use app\index\logic\Sign;
use app\index\model\Sign as SignModel;
use app\index\model\User as UserModel;
use think\Controller;
use think\Loader;

class User extends Common
{
    public function index()
    {
        $this->assign('title',"用户中心");
        return $this->fetch();
    }

    public function set(){
    	// 查用户
    	$user = UserModel::get(session('uid'));
    	//分配变量到模板使用
    	$this->assign('user',$user);
        $this->assign('title',"用户设置");
    	return $this->fetch();
    }

    public function my(){
    	return $this->fetch();
    }

    public function msg(){
    	return $this->fetch();
    }

    public function save()
    {
    	// 接数据 
    	$data = input('post.');

    	$data['uid'] = session('uid');
    	// 加载验证器
    	$validate = Loader::validate('Save');
    	// 判断数据是否通过
		if(!$validate->check($data)){
		    $this->error($validate->getError());
		}

		$user = new UserModel;
		// save方法第二个参数为更新条件
		$res = $user->save($data,['uid' => session('uid')]);

		if($res){
			$this->success("更新成功");
		}else{
			$this->error("更新失败");
		}
    }

    public function upload()
    {
    	$file = request()->file('file');
    
	    // 移动到框架应用根目录/public/uploads/ 目录下
	    if($file){
	        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
	        if($info){

	        	$face = "uploads/".date('Ymd').'/'.$info->getFilename();

	        	$user = new UserModel;
				// save方法第二个参数为更新条件
				$res = $user->save(['face'=>$face],['uid' => session('uid')]);

				session('face',$face);

				$this->error('上传成功');
	        	
	        }else{
	        	$this->success($file->getError());
	            // 上传失败获取错误信息
	        }
	    }
    }

    public function sign()
    {
        $signInfo = Sign::getInfo();

        if($signInfo['is_sign']){
            $this->error("今天已签到");
        }

        $user = SignModel::get(['uid'=>session('uid')]);
        
        if($user){

            $user->stime = time();
            $user->sdate = date('Y-m-d');
            $user->snum = $signInfo['snum']+1;
            $user->save();
        }else{
            $sign = [
                'uid'=>session('uid'),
                'stime'=>time(),
                'sdate'=>date('Y-m-d'),
                'snum'=>1
            ];
            $res  = SignModel::create($sign);
        }

        $res = (new UserModel)->where(['uid'=>session('uid')])->setInc('kiss',$signInfo['kiss']);

        if($res){
            $this->success("签到成功");
        }else{
            $this->error("签到失败");
        }
    }
}
